package com.micro.magupe.auth.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.LinkedHashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.micro.magupe.auth.entity.Dept;
import com.micro.magupe.auth.service.DeptService;
import com.micro.magupe.common.bean.Result;
import com.micro.magupe.common.bean.Tree;
import com.micro.magupe.common.vo.DeptVO;

@RequestMapping("/dept")
@Controller
public class DeptController {

	@Autowired
	DeptService deptService;
	
	@ResponseBody
	@RequestMapping(value="/getById", method=RequestMethod.GET)
	DeptVO getById(@RequestParam String id) throws IllegalAccessException, InvocationTargetException {
		DeptVO deptVO = deptService.getById(id);
		return deptVO;
	}
	
	@GetMapping("/list")
	@ResponseBody
	List<DeptVO> list() {
		LinkedHashMap<String, Object> query = new LinkedHashMap<String, Object>(16);
		List<DeptVO> list = deptService.listQuery(query);
		
		for (DeptVO deptVO : list) {
			deptVO.setParentId(deptVO.getParent().getId());
		}
		
		return list;
	}
	
	@PostMapping("/save")
	@ResponseBody
	Result save(DeptVO deptVO) {
		if (deptService.save(deptVO) > 0) {
			return Result.ok();
		}
		
		return Result.error();
	}
	
	@PostMapping("/update")
	@ResponseBody
	Result update(DeptVO deptVO) {
		if (deptService.update(deptVO) > 0) {
			return Result.ok();
		}
		
		return Result.error();
	}
	
	@GetMapping("/tree")
	@ResponseBody
	public Tree<DeptVO> tree() {
		Tree<DeptVO> tree = new Tree<DeptVO>();
		tree = deptService.getTree();
		return tree;
	}
	
	@PostMapping("/exitName")
	@ResponseBody
	boolean exitName(Dept dept) {
		// 存在，不通过，false
		return !deptService.exitName(dept);
	}
}
